<template>
  <!-- 创建否定关键词投放 -->
  <div class="choose-keyword-w">
    <div class="head">关键词投放</div>
    <div class="choose-product-con flex">
      <div class="choose-list">
        <a-tabs v-model="activeTab">
          <a-tab-pane key="1" title="建议">
            <a-input-group style="margin-bottom: 10px">
              <a-select v-model="bidType" :disabled="isDisabled" style="width: 120px" size="small" @change="defaultBid = null">
                <a-option value="1" label="默认竞价" />
                <a-option value="2" label="自定义竞价" />
                <a-option value="3" label="建议竞价" />
              </a-select>
              <a-input-number v-if="bidType != '2'" disabled size="small" style="width: 200px" :placeholder="(defaultTargetingBid && bidType == '1' ? defaultTargetingBid : '') + ' 直接应用'">
                <template #append>
                  <a-button size="mini">{{ currency }}</a-button>
                </template>
              </a-input-number>
              <a-input-number :disabled="isDisabled" v-else size="small" style="width: 200px" v-model="defaultBid" placeholder="">
                <template #append>
                  <a-button size="mini">{{ currency }}</a-button>
                </template>
              </a-input-number>
            </a-input-group>
            <div class="flex-c" style="margin-bottom: 10px">
              <span>匹配类型：</span>
              <a-checkbox-group :disabled="isDisabled" :min="1" v-model="adviceKeywordTypes" @change="getAdviceListByfilter">
                <a-checkbox value="BROAD" :disabled="adviceKeywordTypes.length === 1 && adviceKeywordTypes[0] === 'BROAD'">广泛</a-checkbox>
                <a-checkbox value="PHRASE" :disabled="adviceKeywordTypes.length === 1 && adviceKeywordTypes[0] === 'PHRASE'">词组</a-checkbox>
                <a-checkbox value="EXACT" :disabled="adviceKeywordTypes.length === 1 && adviceKeywordTypes[0] === 'EXACT'">精准</a-checkbox>
              </a-checkbox-group>
            </div>
            <div class="flex-c" style="margin-bottom: 10px">
              <span>排序：</span>
              <a-select v-model="sortDimension" :disabled="isDisabled" style="width: 120px" size="small" @change="getAdviceList">
                <a-option value="CLICKS" label="按点击次数" />
                <a-option value="CONVERSIONS" label="按订单数量" />
              </a-select>
              <span style="margin-left: 20px">关键词：</span>
              <a-input-search v-model="keywordSeachVal" :disabled="isDisabled" size="small" style="width: 200px" placeholder="输入关键词查询" @search="getAdviceList" />
            </div>
            <a-table size="mini" class="table-normal-line" :loading="tableLoading" :pagination="false" :scroll="{ x: '400', y: '300px' }" :data="adviceBidList">
              <template #columns>
                <a-table-column data-index="keyword">
                  <template #title>
                    <a-popover>
                      <template #content>
                        <p style="width: 400px">展示量份额 (IS) ：是指您在这个词上获得的展示量相对于它产生的所有展示量的百分比。IS 为 0% 表示这个词您没有获得任何展示次数。</p>
                        <p style="width: 400px">展示量排名 (IR)：是指您的 IS 相对于其他广告主在同一个词上获得的展示量份额所占的排名。</p>
                      </template>
                      <p>
                        <span>关键词IS/IR</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                  <template #cell="{ record }">
                    <TextLimit :rows="1">{{ record.keyword }}</TextLimit>
                    <TextLimit :rows="1">{{ record.translation }}</TextLimit>
                    <p>
                      <span>IS {{ record.searchTermImpressionShare || '--' }}%</span>
                      <span style="margin-left: 5px">IR {{ record.searchTermImpressionRank || '--' }}</span>
                    </p>
                  </template>
                </a-table-column>
                <a-table-column title="匹配类型" data-index="keywordMatchType" :width="80">
                  <template #cell="{ record }">
                    <p>{{ KeywordMatchType[record.matchType] }}匹配</p>
                  </template>
                </a-table-column>
                <a-table-column :width="150" data-index="advideBid" title="建议竞价">
                  <template #title>
                    <p>
                      <span>建议竞价</span>
                      <span>({{ currency }})</span>
                    </p>
                  </template>
                  <template #cell="{ record }">
                    <p v-if="record.rangeMedian">{{ record.rangeMedian }}</p>
                    <p v-if="record.rangeStart || record.rangeEnd">{{ record.rangeStart || '--' }} ~ {{ record.rangeEnd || '--' }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="negativeKeyword" :width="80" align="center">
                  <template #title>
                    <p class="highlight cursor" @click="addKeywordByAdvice(adviceBidList)">全部添加</p>
                  </template>
                  <template #cell="{ record }">
                    <a-button type="text" @click="addKeywordByAdvice([record])">添加</a-button>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2" title="输入列表">
            <a-input-group style="margin-bottom: 10px">
              <a-select v-model="bidType" :disabled="isDisabled" style="width: 120px" size="small" @change="defaultBid = null">
                <a-option value="1" label="默认竞价" />
                <a-option value="2" label="自定义竞价" />
                <a-option value="3" label="建议竞价" />
              </a-select>
              <a-input-number v-if="bidType != '2'" disabled size="small" style="width: 200px" :placeholder="(defaultTargetingBid || '') + ' 直接应用'">
                <template #append>
                  <a-button size="mini">{{ currency }}</a-button>
                </template>
              </a-input-number>
              <a-input-number :disabled="isDisabled" v-else size="small" style="width: 200px" v-model="defaultBid" placeholder="">
                <template #append>
                  <a-button size="mini">{{ currency }}</a-button>
                </template>
              </a-input-number>
            </a-input-group>
            <div class="flex-c" style="margin-bottom: 10px">
              <span>匹配类型：</span>
              <a-checkbox-group :disabled="isDisabled" :min="1" v-model="keywordTypes">
                <a-checkbox value="BROAD" :disabled="keywordTypes.length === 1 && keywordTypes[0] === 'BROAD'">广泛</a-checkbox>
                <a-checkbox value="PHRASE" :disabled="keywordTypes.length === 1 && keywordTypes[0] === 'PHRASE'">词组</a-checkbox>
                <a-checkbox value="EXACT" :disabled="keywordTypes.length === 1 && keywordTypes[0] === 'EXACT'">精准</a-checkbox>
              </a-checkbox-group>
            </div>
            <a-textarea :disabled="isDisabled" v-model="keywordVal" placeholder="输入关键词，一行一个" allow-clear style="height: 240px" />
            <div class="flex-c-sb">
              <p>不得包含特殊字符，如@、#、*、$、/等</p>
              <a-button size="mini" v-if="!isDisabled" type="primary" :loading="tableLoading" @click="addKeywordByKeyword">添加</a-button>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
      <div class="checked-list">
        <div class="flex-c" style="margin-bottom: 10px">
          <p style="margin-right: 10px">已添加{{ editSpCampaignInfo.keywordTargetingInfos.length }}个关键词</p>
          <p>(最多可添加1000个)</p>
        </div>
        <a-table size="mini" class="table-normal-line" :pagination="false" :scroll="{ x: '400', y: '320px' }" :data="editSpCampaignInfo.keywordTargetingInfos">
          <template #columns>
            <a-table-column title="关键词IS/IR" data-index="keyword">
              <template #cell="{ record }">
                <TextLimit :rows="1">{{ record.keyword }}</TextLimit>
                <TextLimit :rows="1">{{ record.translation }}</TextLimit>
                <p>
                  <span>IS {{ record.searchTermImpressionShare || '--' }}%</span>
                  <span style="margin-left: 5px">IR {{ record.searchTermImpressionRank || '--' }}</span>
                </p>
              </template>
            </a-table-column>
            <a-table-column title="匹配类型" data-index="keywordMatchType" :width="80">
              <template #cell="{ record }">
                <p>{{ KeywordMatchType[record.keywordMatchType] }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="125" data-index="bid2">
              <template #title>
                <div class="flex-c">
                  <p style="margin-right: 5px">建议竞价</p>
                  <a-popconfirm content="此操作将更新所有已选关键词的竞价，是否继续？" @ok="useAdviceBid" type="warning">
                    <a-button type="text">应用所有</a-button>
                  </a-popconfirm>
                </div>
              </template>
              <template #cell="{ record }">
                <p v-if="record.rangeMedian">{{ record.rangeMedian }}</p>
                <p v-if="record.rangeStart || record.rangeEnd">{{ record.rangeStart || '--' }} ~ {{ record.rangeEnd || '--' }}</p>
              </template>
            </a-table-column>
            <a-table-column title="竞价" data-index="bid" :width="120">
              <template #title>
                <p>
                  <span>竞价</span>
                  <span class="warningColor">*</span>
                  <span>({{ currency }})</span>
                </p>
              </template>
              <template #cell="{ record }">
                <a-input-number :disabled="isDisabled" size="mini" style="width: 90px" v-model="record.bid" placeholder="" allow-clear />
              </template>
            </a-table-column>
            <a-table-column data-index="negativeKeyword" :width="80">
              <template #title>
                <p class="highlight cursor" @click="editSpCampaignInfo.keywordTargetingInfos = []" v-if="!isDisabled">删除所有</p>
              </template>
              <template #cell="{ rowIndex }">
                <icon-close-circle class="cursor" style="font-size: 16px" @click="deleteKeyword(rowIndex)" v-if="!isDisabled" />
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, onMounted, watch } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { KeywordMatchType, DraftFinishStep } from '../../types'
  import { marketPlaceList } from '@/utils/globalData'
  import { keywordRecommendation } from '@/api/advert'
  const props = defineProps({
    darftInfo: {
      type: Object,
      default: () => {},
    },
    defaultTargetingBid: {
      type: [String, Number],
    },
    shop: {
      type: Object,
      default: () => {},
    },
    adType: {
      type: String,
      default: 'SPONSORED_PRODUCTS',
    },
    products: {
      type: Array,
      default: () => [],
    },
    spKeywordRecommendationType: {
      type: String,
      default: 'KEYWORDS_FOR_ASINS',
    },
    campaignId: {
      type: String,
    },
    adGroupId: {
      type: String,
    },
  })
  onMounted(() => {
    editSpCampaignInfo.value.keywordTargetingInfos = props.darftInfo?.keywordTargetingInfos || []
    getAdviceList()
  })
  const keywordTypes = ref(['BROAD'])
  const adviceKeywordTypes = ref(['BROAD'])
  const editSpCampaignInfo = ref<any>({
    keywordTargetingInfos: [],
  })
  const keywordVal = ref()
  const bidType = ref('1')
  const activeTab = ref('1')
  const sortDimension = ref('CLICKS')
  const defaultBid = ref()
  const keywordSeachVal = ref()
  const adviceBidList = ref<Array<any>>([])
  const tableLoading = ref(false)
  const currency = computed(() => {
    let marketplaceId = props.shop?.marketplaceId
    return marketplaceId ? marketPlaceList[marketplaceId]?.currency : 'USD'
  })
  const asins = computed(() => {
    return props.products?.map((el: any) => el.asin)
  })
  // 根据当前流程节点判断是否可编辑
  let isDisabled = computed(() => {
    let handlerFlow = props.darftInfo?.handlerFlow || 'INIT'
    let level = DraftFinishStep[handlerFlow]
    return Number(level) > 3 ? true : false
  })
  // 根据筛选条件查询建议搜索列表
  function getAdviceListByfilter() {
    if (keywordSeachVal.value && adviceKeywordTypes.value.length) {
      getAdviceList()
    }
  }
  // 获取建议搜索列表
  async function getAdviceList() {
    tableLoading.value = true
    let keyWords = keywordSeachVal.value ? [keywordSeachVal.value] : []
    adviceBidList.value = await requestAdviceBid(keyWords, adviceKeywordTypes.value)
    tableLoading.value = false
  }
  // 请求获取建议竞价信息
  async function requestAdviceBid(keyWords: Array<any>, keywordTypes: Array<any>) {
    if (!props.shop?.id) return []
    let shopKeywordInfo: any = {
      adType: props.adType,
      maxRecommendations: 50,
    }
    if (props.adType == 'SPONSORED_PRODUCTS') {
      shopKeywordInfo.sortDimension = sortDimension.value
      shopKeywordInfo.spKeywordRecommendationType = props.spKeywordRecommendationType
    }
    // 根据商品获取建议关键词
    if (props.spKeywordRecommendationType == 'KEYWORDS_FOR_ASINS') {
      if (!asins.value?.length) return []
      shopKeywordInfo.asins = asins.value
    }
    // 根据广告活动&广告组获取建议关键词
    if (props.spKeywordRecommendationType == 'KEYWORDS_FOR_ADGROUP') {
      if (!props.campaignId || !props.adGroupId) return []
      shopKeywordInfo.campaignId = props.campaignId
      shopKeywordInfo.adGroupId = props.adGroupId
    }
    // 根据匹配类型和关键词查询
    if (keyWords.length && keywordTypes.length) {
      shopKeywordInfo.keywordInfoBOs = []
      shopKeywordInfo.maxRecommendations = 0
      keyWords.forEach((val: string) => {
        keywordTypes.forEach((type: string) => {
          shopKeywordInfo.keywordInfoBOs.push({
            keyword: val,
            matchType: type,
          })
        })
      })
    }
    const res: any = await keywordRecommendation([
      {
        shopId: props.shop.id,
        shopKeywordInfo: shopKeywordInfo,
      },
    ])
    return res?.data?.[0]?.keywordInfos || []
  }
  // 添加关键词
  function addKeyword(list: Array<any>) {
    // 去重
    list.forEach((el: any) => {
      let _index = editSpCampaignInfo.value.keywordTargetingInfos.findIndex((item: any) => item.keyword == el.keyword && item.keywordMatchType == el.keywordMatchType)
      if (_index == -1 && editSpCampaignInfo.value.keywordTargetingInfos.length < 1000) {
        editSpCampaignInfo.value.keywordTargetingInfos.push(el)
      }
    })
  }
  // 添加建议关键词
  function addKeywordByAdvice(list: Array<any>) {
    let newList: Array<any> = []
    list.forEach((el: any) => {
      let bid = bidType.value === '3' ? el.bid : bidType.value === '1' ? props.defaultTargetingBid : defaultBid.value
      newList.push({
        ...el,
        bid: bid,
        keywordMatchType: el.matchType,
      })
    })
    addKeyword(newList)
  }
  // 输入关键词添加
  async function addKeywordByKeyword() {
    if (!keywordVal.value) {
      Message.error('请输入关键词')
      return
    }
    const reg = new RegExp('[~!@#$^&*=《》?！@#￥&*{}【】‘；：。，、？]')
    if (reg.test(keywordVal.value)) {
      Message.error('不得包含特殊字符，如@、#、*、$、/等')
      return
    }
    // let bid = bidType.value === '1' ? props.defaultTargetingBid : defaultBid.value
    let keywords = keywordVal.value.split('\n')
    keywords = keywords.filter((val: string) => val?.trim())
    // 通过关键词和类型获取建议竞价
    tableLoading.value = true
    let adviceBids = await requestAdviceBid(keywords, keywordTypes.value)
    let adviceBidsMap: any = {}
    adviceBids.forEach((el: any) => {
      let key = el.keyword + el.matchType
      el.keywordMatchType = el.matchType
      adviceBidsMap[key] = el
    })
    tableLoading.value = false
    // 设置添加关键词的格式
    console.log(adviceBids)
    let list: Array<any> = []
    keywords.forEach((val: string) => {
      keywordTypes.value.forEach((type: string) => {
        let key = val + type
        let bid = bidType.value === '3' ? adviceBidsMap[key]?.bid : bidType.value === '1' ? props.defaultTargetingBid : defaultBid.value
        let obj = {
          ...(adviceBidsMap[key] || {}),
          keyword: val,
          keywordMatchType: type,
          bid: bid,
        }
        list.push(obj)
      })
    })
    console.log(list)
    addKeyword(list)
  }
  //批量应用建议竞价
  function useAdviceBid() {
    editSpCampaignInfo.value.keywordTargetingInfos.forEach((el: any) => {
      if (el.rangeMedian) {
        el.bid = el.rangeMedian
      }
    })
  }
  // 刪除产品
  function deleteKeyword(i: number) {
    editSpCampaignInfo.value.keywordTargetingInfos.splice(i, 1)
  }
  // 校验信息
  async function validateData() {
    let arrs = editSpCampaignInfo.value.keywordTargetingInfos
    let noBid = arrs.some((el: any) => !(el.bid === 0 || el.bid))
    if (noBid) {
      Message.error('关键字投放竞价必填')
      return false
    }
    return true
  }
  // 设置需要创建的数据
  function setCreateData() {
    return {
      keywordTargetingInfos: editSpCampaignInfo.value.keywordTargetingInfos,
    }
  }
  watch(asins, () => {
    // 根据asin获取建议关键词的时候动态监听asin
    if (props.spKeywordRecommendationType == 'KEYWORDS_FOR_ASINS') {
      getAdviceList()
    }
  })
  watch(
    () => [props.campaignId, props.adGroupId],
    () => {
      // 根据广告组广告活动获取建议关键词的时候动态监听
      if (props.spKeywordRecommendationType == 'KEYWORDS_FOR_ADGROUP') {
        getAdviceList()
      }
    }
  )
  defineExpose({ validateData, setCreateData })
</script>
<style lang="less" scoped>
  .edit-header {
    background-color: var(--color-fill-2) !important;
    border-left: 2px solid rgb(var(--primary-6));
    line-height: 32px;
    font-size: 16px;
    margin-bottom: 20px;
    padding-left: 20px;
  }
  .choose-keyword-w {
    border: 1px solid var(--color-border);
    .head {
      padding: 6px 20px;
      border-bottom: 1px solid var(--color-border);
    }
    :deep(.arco-tabs-pane) {
      padding: 10px 20px;
    }
    .choose-list {
      width: 50%;
      border-right: 1px solid var(--color-border);
      flex-shrink: 0;
    }
    .checked-list {
      padding: 10px 20px;
      overflow: hidden;
      flex: 1;
    }
    :deep(.arco-input-append) {
      padding: 0;
      .arco-btn {
        padding: 0 3px;
      }
    }
  }
</style>
